/*
 * 全局请求封装
 * @param path 请求路径
 * @param method 请求类型(GET/POST/DELETE等)
 * @oaram data 请求体数据
 * @param loading 请求未完成是是否显示加载中，默认为true
 */
export default (path, method, data = {}, extendObj) => {
  // 获取存储token
  const token = uni.getStorageSync("token");

  // 根据token进行调用函数
  if (token != "") {
    return tokenRequest(path, method, data, extendObj, token);
  } else {
    return noTokenRequest(path, method, data, extendObj);
  }
};

// 无token时发送请求函数
function noTokenRequest(path, method, data, extendObj) {
  return new Promise((resolve, reject) => {
    const obj = {
      url: path,
      method,
      data,
      success(response) {
        if (response.header.token) {
          uni.setStorageSync("token", response.header.token);
        }
        let { data } = response;
        if (data && data.code == 200) {
          resolve(data);
        } else if (data.code == 2003) {
          uni.showToast({
            title: data?.msg || "服务响应失败",
            icon: "none",
          });
          resolve(data);
        } else {
          uni.showToast({
            title: data?.msg || data?.data || "服务响应失败",
            icon: "none",
          });
          resolve(data);
        }
      },
      fail(err) {
        uni.showToast({
          icon: "none",
          title: err.errorMsg || "服务响应失败",
        });
        console.error(err);
        reject(err);
      },
      complete() {},
    };
    if (extendObj) {
      Object.assign(obj, extendObj);
    }
    uni.request(obj);
  });
}

// 有token时发送请求函数
function tokenRequest(path, method, data, extendObj, token) {
  return new Promise((resolve, reject) => {
    const obj = {
      url: path,
      method,
      data,
      header: {
        token,
      },
      success(response) {
        if (response.header.token) {
          uni.setStorageSync("token", response.header.token);
        }
        if (response.data.errorCode === "00017") {
          uni.removeStorageSync("token");
        }
        resolve(response.data);
      },
      fail(err) {
        uni.showToast({
          icon: "none",
          title: err.errorMsg || "服务响应失败",
        });
        console.error(err);
        reject(err);
      },
      complete() {},
    };
    if (extendObj) {
      Object.assign(obj, extendObj);
    }
    uni.request(obj);
  });
}
